package com.ruoyi.controller;

import java.math.BigDecimal;
import java.util.List;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.config.AlipayConf;
import com.ruoyi.domainVo.TCwPaymentPlanVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.domain.TCwPaymentPlan;
import com.ruoyi.service.ITCwPaymentPlanService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 付款计划管理Controller
 * 
 * @author ruoyi
 * @date 2023-03-02
 */
@RestController
@RequestMapping("/plan")
public class TCwPaymentPlanController extends BaseController
{
    @Autowired
    private ITCwPaymentPlanService tCwPaymentPlanService;

    /**
     * 查询付款计划管理列表
     */
    @RequiresPermissions("property:plan:list")
    @GetMapping("/list")
    public TableDataInfo list(TCwPaymentPlanVo tCwPaymentPlan)
    {
        startPage();
        List<TCwPaymentPlan> list = tCwPaymentPlanService.selectTCwPaymentPlanListByTabs(tCwPaymentPlan);
        return getDataTable(list);
    }

    /**
     * 导出付款计划管理列表
     */
    @RequiresPermissions("property:plan:export")
    @Log(title = "付款计划管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TCwPaymentPlan tCwPaymentPlan)
    {
        List<TCwPaymentPlan> list = tCwPaymentPlanService.selectTCwPaymentPlanList(tCwPaymentPlan);
        ExcelUtil<TCwPaymentPlan> util = new ExcelUtil<TCwPaymentPlan>(TCwPaymentPlan.class);
        util.exportExcel(response, list, "付款计划管理数据");
    }

    /**
     * 获取付款计划管理详细信息
     */
    @RequiresPermissions("property:plan:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tCwPaymentPlanService.selectTCwPaymentPlanById(id));
    }
    /**
     * 定时任务获取列表
     * @return
     */
    @RequestMapping ("/getInfoByOpen")
    public List<TCwPaymentPlan> getInfoByOpen()
    {
        List<TCwPaymentPlan> tCwPaymentPlans = tCwPaymentPlanService.selectTCwPaymentPlanListByApply();
        return tCwPaymentPlans;
    }

    /**
     * 新增付款计划管理
     */
    @RequiresPermissions("property:plan:add")
    @Log(title = "付款计划管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCwPaymentPlan tCwPaymentPlan)
    {
        return toAjax(tCwPaymentPlanService.insertTCwPaymentPlan(tCwPaymentPlan));
    }

    /**
     * 修改付款计划管理
     */
    @RequiresPermissions("property:plan:edit")
    @Log(title = "付款计划管理", businessType = BusinessType.UPDATE)
    @GetMapping("/edit")
    public R edit( TCwPaymentPlan tCwPaymentPlan)
    {
        return R.ok(tCwPaymentPlanService.updateTCwPaymentPlan(tCwPaymentPlan));
    }

    /**
     * 删除付款计划管理
     */
    @RequiresPermissions("property:plan:remove")
    @Log(title = "付款计划管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tCwPaymentPlanService.deleteTCwPaymentPlanByIds(ids));
    }


    /**
     * 支付回调
     * @param response
     * @param out_trade_no
     * @param total_amount
     * @throws IOException
     */

    @RequestMapping("/ren")
    public void ren(HttpServletResponse response,String out_trade_no, BigDecimal total_amount) throws IOException {
        String[] split = out_trade_no.split("-");
        String id=split[split.length-1];
        //修改数据库状态
        TCwPaymentPlan tCwPaymentPlan = new TCwPaymentPlan();
        tCwPaymentPlan.setPaymentId(Integer.parseInt(id));
        tCwPaymentPlan.setPayMethod(2L);
        //付款单号
        tCwPaymentPlan.setReserve1(out_trade_no);
        tCwPaymentPlanService.updateTCwPaymentPlan(tCwPaymentPlan);
        response.sendRedirect("http://localhost/property/plan");
    }

    /**
     * 支付
     * @param response
     * @param price
     * @param id
     */
    @RequestMapping("/cz")
    public void pay(HttpServletResponse response,Double price,String id){
        AlipayClient client = new DefaultAlipayClient(AlipayConf.URL, AlipayConf.APPID, AlipayConf.RSA_PRIVATE_KEY, AlipayConf.FORMAT, AlipayConf.CHARSET, AlipayConf.ALIPAY_PUBLIC_KEY,AlipayConf.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
        //新建付款实体类
        TCwPaymentPlan tCwPaymentPlan = new TCwPaymentPlan();
        String payNo=UUID.randomUUID()+"-"+id;
        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(payNo);
        model.setSubject("付款");
        model.setTotalAmount(price.toString());
        model.setBody("body");
        model.setTimeoutExpress("2ms");
        model.setProductCode("product_code");
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConf.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConf.return_url);
        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AlipayConf.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
